//
//  networkTool.swift
//  微博
//
//  Created by 王朝阳 on 16/4/9.
//  Copyright © 2016年 王朝阳. All rights reserved.
//

import UIKit
import AFNetworking

enum HMRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class networkTool: AFHTTPSessionManager
{
    /// 网络请求完成回调，类似于 OC 的 typeDefine
    typealias HMRequestCallBack = (result: AnyObject?, error: NSError?)->()
    static let sharemanager: networkTool = {
        
        let tools = networkTool(baseURL: nil)
        
        // 设置反序列化数据格式 - 系统会自动将 OC 框架中的 NSSet 转换成 Set
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
        
    }()

}
extension networkTool {
    
    private func request(method: HMRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished: (result: AnyObject?, error: NSError?)->()
) {
        
//        // 定义成功回调
//        let success = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
//            finished(result: result, error: nil)
//        }
//        
//        // 定义失败回调
//        let failure = { (task: NSURLSessionDataTask, error: NSError) -> Void in
//            // 在开发网络应用的时候，错误不要提示给用户，但是错误一定要输出！
//            print(error)
//            finished(result: nil, error: error)
//        }
        
        if method == HMRequestMethod.GET {
            GET(URLString, parameters: parameters, success: { (_, result) -> Void in
                finished(result: result, error: nil)
                }, failure: { (_, error) -> Void in
                    finished(result: nil, error: error)
 
            })
            
        } else {
            POST(URLString, parameters: parameters, success: { (_, result) -> Void in
                finished(result: result, error: nil)
                }, failure: { (_, error) -> Void in
                    finished(result: nil, error: error)
                    
            })
        }
    }

}
